import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';

import '../video_play/video_player_page.dart';

class VideoListPage extends StatelessWidget {
  final AssetPathEntity pathEntity;

  const VideoListPage({super.key, required this.pathEntity});

  // 异步获取文件夹下的视频列表
  Future<List<AssetEntity>> _fetchVideos() async {
    return await pathEntity.getAssetListRange(start: 0, end: await pathEntity.assetCountAsync);
  }

  // 构建视频列表项
  Widget _buildVideoListItem(AssetEntity video, List<AssetEntity> all) {
    return FutureBuilder<Uint8List?>(
      future: video.thumbnailData, // 获取视频的缩略图数据
      builder: (context, snapshot) {
        final thumbnail = snapshot.data;

        return ListTile(
          leading: thumbnail != null ? Image.memory(thumbnail, width: 64, height: 64, fit: BoxFit.cover) : Container(width: 64, height: 64, color: Colors.grey),
          title: Text(video.title ?? '未知视频'),
          subtitle: Text(
            '大小: ${(video.originFile).toString()} M, 时长: ${(video.duration / 60).toStringAsFixed(2)} 分钟',
          ),
          onTap: () {
            Get.to(() => VideoPlayerPage(videoFile: video, videoList: all));
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('视频列表'),
      ),
      body: FutureBuilder<List<AssetEntity>>(
          future: _fetchVideos(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }

            if (snapshot.hasError) {
              return Center(child: Text('加载视频失败: ${snapshot.error}'));
            }

            final videos = snapshot.data ?? [];

            if (videos.isEmpty) {
              return Center(child: Text('没有视频文件'));
            }
            return ListView.separated(
              itemCount: videos.length,
              separatorBuilder: (BuildContext context, int index) => Divider(),
              itemBuilder: (BuildContext context, int index) {
                final video = videos[index];
                return _buildVideoListItem(video, videos);
              },
            );
          }),
    );
  }
}
